<template>
    <el-breadcrumb separator-icon="ArrowRight" style="margin-bottom: 50px;">
        <el-breadcrumb-item>项目管理</el-breadcrumb-item>
        <el-breadcrumb-item>项目列表</el-breadcrumb-item>
        <el-breadcrumb-item>添加项目</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form ref="addRuleForm" label-width="100px" :model="field" :rules="form_rules">
        <el-form-item label="上传项目：">
            <el-form-item>
                <el-upload class="upload-demo" drag action="" :show-file-list="true" :auto-upload="false" :limit="1"
                    accept=".zip," :on-change="handleChange">
                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                    <div class="el-upload__text">
                        将文件拖拽到此处 <em>点击上传</em>
                    </div>
                    <template #tip>
                        <div class="el-upload__tip">
                            只能上传一个文件（后缀为.zip）,大小不超过10MB
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
        </el-form-item>
        <el-form-item label="项目名称：" prop="name">
            <el-input v-model="field.name" placeholder="请输入项目名称"></el-input>
        </el-form-item>
        <el-form-item label="项目版本：" prop="version">
            <el-input v-model="field.version" placeholder="请输入项目版本"></el-input>
        </el-form-item>
        <el-form-item label="项目详情：" prop="description">
            <el-input v-model="field.description" type="textarea" placeholder="请输入项目详情"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="success" @click="submitForm('addRuleForm')">提交</el-button>
            <el-button type="danger" @click="resetForm">重置</el-button>
        </el-form-item>
    </el-form>
</template>

<script>
import { reactive, getCurrentInstance, onMounted, ref } from 'vue';
import { UploadFilled } from '@element-plus/icons-vue'
import { useRouter, useRoute } from "vue-router";
import { InfoCreate, InfoAnalysis } from "../../api/http.js"
import { requestHook } from '../../components/table/requestHook'

export default {
    name: "ProjectAdd",
    setup(props) {
        var login_userid = localStorage.getItem("userid")
        const { go } = useRouter();
        const router = useRouter()
        const { push } = useRouter();
        const { loadData } = requestHook();

        const field = reactive({
            name: "",
            version: "",
            description: "",
        })
        const form_rules = reactive({
            name: [{ required: true, message: "项目名称不能为空", trigger: 'blur' }],
            version: [{ required: true, message: "项目版本不能为空", trigger: 'blur' }],
            description: [{ required: true, message: "项目详情不能为空", trigger: 'blur' }],

        })
        const { proxy } = getCurrentInstance()
        // 上传文件数组
        const fileList = ref([])

        // 文件改变时回调钩子
        const handleChange = (file, files) => {
            // file是当前上传的文件，files是当前所有的文件，
            //const isZIP = file.type === 'application/x-zip-compressed' //限制上传zip格式文件
            const isZIP = file.name.substring(file.name.lastIndexOf('.') + 1) === 'zip'
            const isLt10M = file.size / 1024 / 1024 < 10    //文件大小不能超过10MB
            if (!isZIP) {
                proxy.$message.error("上传文件只能是ZIP格式!");
                files.splice(-1, 1);//从文件列表中删除
                return false
            }
            if (!isLt10M) {
                proxy.$message.error("上传文件大小不能超过10MB!");
                files.splice(-1, 1);
                return false
            }
            fileList.value = files
            console.log(fileList.value)
            fileList.value.forEach(item => {
                //这里有个坑， item其实并不是真是数据 item.raw才是
                console.log(item)
            })
        }


        //const uploadSuccess = (response, file, fileList) => {}

        const submitForm = () => {
            proxy.$refs.addRuleForm.validate((valid) => {
                console.log(fileList.value.length)
                if (fileList.value.length === 0) {
                    proxy.$message.error("请选择需要上传的文件!");
                }
                else if (valid) {
                    const form = new FormData()
                    fileList.value.forEach(item => {
                        form.append('files', item.raw)
                    })
                    //console.log(form.get('files'));
                    form.append("userid", login_userid)
                    form.append("name", field.name)
                    form.append("version", field.version)
                    form.append("description", field.description)
                    //console.log(form.get('userid'));
                    InfoCreate(form).then(response => {
                        console.log("添加项目=>", response.data)
                        if (response.data.code === 200) {
                            // 弹窗提示
                            proxy.$message.success("添加成功!开始解析项目!");
                            // 重置表单
                            resetForm()
                            router.push('/home/projectList')
                            const req = {
                                projectid: response.data.data.projectid,
                            }//得到添加项目成功后返回响应内容的项目id
                            console.log("req=>", req)

                            /** 启动分析 */
                            InfoAnalysis(req).then(resAnalysis => {
                                if (resAnalysis.data.code === 200) {
                                    //window.location.reload()
                                    //proxy.$message.success("解析完成！");
                                    // push({
                                    //     path: "/projectViewTotal/projectWholeInfo",
                                    // })
                                    // localStorage.setItem("projectid", projectid)
                                }
                                window.location.reload()
                            }).catch(error => {
                                console.log(error);
                            })
                        }else if(response.data.code === 400){
                            proxy.$message.error(response.data.message);
                            fileList.value.splice(-1, 1);
                            proxy.$message.info("请重新上传文件！");
                        }else{
                            proxy.$message.error(response.data.message);
                        }

                    }).catch(error => {
                        console.log(error);
                    })
                } else {
                    console.log('error submit!!')
                    proxy.$message.error("添加失败!");
                    return false
                }
            })
        }

        //定义可重用函数和初始数据
        const originData = () => ({
            name: "",
            version: "",
            description: "",
        });

        // 重置
        const resetForm = () => {
            // addRuleForm.value = { ...field }
            // Object.assign(form_data.field, originData());//也是重置的一种方法
            //addRuleForm.value.resetFields();
            fileList.value.splice(-1, 1);
            proxy.$refs.addRuleForm.resetFields();
        }

        onMounted(() => {
            Object.assign(field, originData());
        })

        return {
            field,
            form_rules,
            fileList,
            // ...toRefs(form_data),
            submitForm,
            resetForm,
            handleChange,
        }
    }
}
</script>

<style scoped>
.upload-demo {
    width: 500px;
}
</style>  